﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32;

namespace SysLock
{
    public partial class Classic : Form
    {
        #region Attributes

        #region Private

        private static Size SmallSize = new Size(10, 10);
        private static Size BigSize = new Size(100, 100);

        private static bool IsRunning = false;
        private static bool IsHide = false;

        private static Thread myThread = null;

        private static string IniPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\SysLock";
        private static string IniFile = @"\Setting.ini";

        #endregion

        #region Public

        public static string Interval = "15";
        public static string picType = "1";
        public static string picPath = "";
        public static string autoStart = "0";

        #endregion

        #endregion

        #region Form

        public Classic(string[] args)
        {
            InitializeComponent();
            if (args.Length > 0 && args[0].ToUpper() == "HIDE") IsHide = true;
        }

        private void Classic_Shown(object sender, EventArgs e)
        {
            InitForm();

            SmallSize = new Size(this.Size.Width, this.Size.Height);
            BigSize = new Size(this.Size.Width, this.Size.Height + this.panel1.Height + 25);

            if (IsHide == true)
            {
                this.notifyIcon1.Visible = true;
                this.Hide();
            }
            else
            {
                this.notifyIcon1.Visible = true;
                this.WindowState = FormWindowState.Normal;
            }

            if (autoStart == "1") btnStart_Click(sender, e);
        }

        private void Classic_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.notifyIcon1.Visible = true;
                this.Hide();
            }
        }

        private void Classic_DoubleClick(object sender, EventArgs e)
        {
            if (this.Size == SmallSize) this.Size = BigSize;
            else this.Size = SmallSize;
        }

        private void Classic_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            if (myThread != null && myThread.IsAlive)
            {
                if (MessageBox.Show("程序正在运行中，确认要退出吗?", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    myThread.Abort();
                }
                else
                {
                    return;
                }
            }
            e.Cancel = false;
        }

        #endregion

        #region Event

        #region Button

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (IsRunning == false)
            {
                Regex regex = new Regex(@"^\d+$");
                if (!regex.IsMatch(this.tbTime.Text))
                {
                    MessageBox.Show("请输入整数");
                    return;
                }

                this.btnStart.Text = "取消";
                IsRunning = true;

                myThread = new Thread(new ThreadStart(LockThread));
                myThread.Start();
            }
            else
            {
                myThread.Abort();
                this.btnStart.Text = "启动";
                IsRunning = false;
            }
        }

        private void btnView_Click(object sender, EventArgs e)
        {
            string type = "1";
            string path = "";
            if (this.rbtnWin7.Checked) type = "1";
            if (this.rbtnWin8.Checked) type = "2";
            if (this.rbtnUserDefine.Checked)
            {
                if (this.tbPicPath.Text.Length == 0)
                {
                    MessageBox.Show("请选择自定义图片");
                    return;
                }
                else
                {
                    type = "0";
                    path = this.tbPicPath.Text;
                }
            }

            Lock mylock = new Lock(type, path);
            try
            {
                mylock.ShowDialog();
            }
            finally
            {
                mylock.Dispose();
            }
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            SaveSetting();
            MessageBox.Show("配置已保存");
        }

        #endregion

        #region ToolStripMenuItem

        private void ToolStripMenuItem_exit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        #endregion

        #region CheckBox

        private void cbAutoRun_Click(object sender, EventArgs e)
        {
            //打开注册表
            RegistryKey regKey = Registry.CurrentUser;
            string SubKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Run";
            RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true);
            if (optionKey == null)
            {
                MessageBox.Show(@"设置失败");
            }

            //更改健值，设置代理，
            try
            {
                if (this.cbAutoRun.Checked)
                {
                    this.cbAutoStart.Checked = true;
                    optionKey.SetValue("SysLock", Application.ExecutablePath + " Hide");
                    MessageBox.Show("已设置为开机启动");
                }
                else
                {
                    optionKey.DeleteValue("SysLock", false);
                    MessageBox.Show("已关闭开机启动");
                }
            }
            catch
            {
                MessageBox.Show("设置失败");
            }
            finally
            {
                optionKey.Close();
            }
        }

        #endregion

        #region notifyIcon

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
        }

        #endregion

        #region TextBox

        private void tbPicPath_DoubleClick(object sender, EventArgs e)
        {
            OpenFileDialog myDialog = new OpenFileDialog();

            try
            {
                myDialog.AddExtension = false;
                myDialog.CheckFileExists = true;
                myDialog.ValidateNames = true;
                myDialog.Filter = "Image files (*.jpg;*.bmp;*.gif;*.png)|*.gif;*.jpg;*.bmp;*.png";
                myDialog.FilterIndex = 1;
                if (myDialog.ShowDialog() == DialogResult.Cancel)
                {
                    return;
                }

                this.tbPicPath.Text = myDialog.FileName;
            }
            finally
            {
                myDialog.Dispose();
            }
        }

        #endregion

        #region RadioButton

        private void rbtnUserDefine_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rbtnUserDefine.Checked) this.tbPicPath.Enabled = true;
            else this.tbPicPath.Enabled = false;
        }

        #endregion

        #endregion

        #region LockMethod

        private void LockThread()
        {
            bool b = true;
            while (b)
            {
                try
                {
                    if (GetIdleTick() >= int.Parse(Interval) * 1000)
                    {
                        Lock mylock = new Lock(picType, picPath);
                        try
                        {
                            mylock.ShowDialog();
                        }
                        finally
                        {
                            mylock.Dispose();
                        }
                    }
                    Thread.Sleep(1000);
                }
                catch (ThreadAbortException)
                {
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
        }

        private static long GetIdleTick()
        {
            LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
            lastInputInfo.cbSize = Marshal.SizeOf(lastInputInfo);
            if (!SafeNativeMethods.GetLastInputInfo(ref lastInputInfo)) return 0;
            return Environment.TickCount - (long)lastInputInfo.dwTime;
        }

        #endregion

        #region SettingMethod

        private void SaveSetting()
        {
            #region CheckUserInput

            Regex regex = new Regex(@"^\d+$");
            if (!regex.IsMatch(this.tbTime.Text))
            {
                MessageBox.Show("请输入整数");
                return;
            }
            if (!(this.rbtnWin7.Checked || this.rbtnWin8.Checked || this.rbtnUserDefine.Checked))
            {
                MessageBox.Show("请选择图片");
                return;
            }
            if (this.rbtnUserDefine.Checked && this.tbPicPath.Text.Length == 0)
            {
                MessageBox.Show("请选择自定义图片");
                return;
            }

            #endregion

            #region Save

            if (!Directory.Exists(IniPath)) Directory.CreateDirectory(IniPath);
            QT.IO.INIFile myIni = new QT.IO.INIFile(IniPath + IniFile);
            myIni.WriteInivalue("User", "Interval", this.tbTime.Text);
            Interval = this.tbTime.Text;
            if (this.rbtnWin7.Checked)
            {
                myIni.WriteInivalue("User", "picType", "1");
                picType = "1";
            }
            if (this.rbtnWin8.Checked)
            {
                myIni.WriteInivalue("User", "picType", "2");
                picType = "2";
            }
            if (this.rbtnUserDefine.Checked)
            {
                myIni.WriteInivalue("User", "picType", "0");
                myIni.WriteInivalue("User", "picPath", this.tbPicPath.Text);
                picType = "0";
                picPath = this.tbPicPath.Text;
            }
            if (this.cbAutoRun.Checked) myIni.WriteInivalue("User", "AutoRun", "1");
            else myIni.WriteInivalue("User", "AutoRun", "0");
            if (this.cbAutoStart.Checked) myIni.WriteInivalue("User", "AutoStart", "1");
            else myIni.WriteInivalue("User", "AutoStart", "0");

            #endregion
        }

        private void InitForm()
        {
            QT.IO.INIFile myIni = new QT.IO.INIFile(IniPath + IniFile);
            string t_Interval = "1";
            if (myIni.ReadInivalue("User", "Interval", out t_Interval))
            {
                this.tbTime.Text = t_Interval;
                Interval = t_Interval;
            }
            string t_picType = "1";
            if (myIni.ReadInivalue("User", "picType", out t_picType))
            {
                this.tbPicPath.Enabled = false;
                picType = t_picType;
                switch (t_picType)
                {
                    case "0":
                        this.rbtnUserDefine.Checked = true;
                        string t_picPath = "";
                        if (myIni.ReadInivalue("User", "picPath", out t_picPath))
                        {
                            picPath = t_picPath;
                            this.tbPicPath.Text = t_picPath;
                        }
                        break;
                    case "2":
                        this.rbtnWin8.Checked = true;
                        break;
                    default:
                        this.rbtnWin7.Checked = true;
                        break;
                }
            }
            string t_AutoRun = "0";
            if (myIni.ReadInivalue("User", "AutoRun", out t_AutoRun))
            {
                if (t_AutoRun == "1") this.cbAutoRun.Checked = true;
                else this.cbAutoRun.Checked = false;
            }
            string t_AutoStart = "0";
            if (myIni.ReadInivalue("User", "AutoStart", out t_AutoStart))
            {
                if (t_AutoStart == "1") this.cbAutoStart.Checked = true;
                else this.cbAutoStart.Checked = false;
                autoStart = t_AutoStart;
            }
        }

        #endregion
    }
}
